package linc.cool.robot.simple;

import catcode.CatCodeUtil;
import catcode.CodeBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mzlion.easyokhttp.HttpClient;
import linc.cool.robot.clip.ClipWebContentInfo;
import linc.cool.robot.clip.response.ClipWebResponse;
import linc.cool.robot.constants.ClipWebConstants;
import lombok.extern.slf4j.Slf4j;
import love.forte.simbot.annotation.Filter;
import love.forte.simbot.annotation.FilterValue;
import love.forte.simbot.annotation.OnGroup;
import love.forte.simbot.api.message.containers.GroupAccountInfo;
import love.forte.simbot.api.message.containers.GroupInfo;
import love.forte.simbot.api.message.events.GroupMsg;
import love.forte.simbot.api.sender.MsgSender;
import love.forte.simbot.filter.MatchType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yqlin
 * @date 2022/4/6 17:05
 * @description
 */
@Slf4j
@Component("simpleBotClipWebEvent")
public class SimpleBotClipWebEvent {

    @Value("${qq.group}")
    private String groupCode;

    @Value("${qq.owner}")
    private String ownerCode;

    private final CatCodeUtil catCodeUtil = CatCodeUtil.INSTANCE;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void initAuthToken() {
        doSetAuthToken();
        log.info("auth-token: {}", stringRedisTemplate.opsForValue().get(ClipWebConstants.AUTH_TOKEN));
    }

    private void doSetAuthToken() {
        var response = HttpClient
                .get(ClipWebConstants.BASIC_URI + "/auth")
                .queryString("appId", ClipWebConstants.APPID)
                .queryString("mail", ClipWebConstants.MAIL)
                .asBean(ClipWebResponse.class);
        stringRedisTemplate.opsForValue().setIfAbsent(ClipWebConstants.AUTH_TOKEN, response.getData().toString(), 12, TimeUnit.HOURS);
    }


    @OnGroup
    @Filter(value = "list_clip_title_like\s(?<title>.{1,30})", matchType = MatchType.REGEX_MATCHES, trim = true)
    public void doGroupMsg(GroupMsg event, MsgSender sender, @FilterValue("title") String title) {
        GroupInfo groupInfo = event.getGroupInfo();
        if (groupCode.equals(groupInfo.getGroupCode())) {
            String authToken = stringRedisTemplate.opsForValue().get(ClipWebConstants.AUTH_TOKEN);
            if (authToken == null || authToken.equals("")) {
                doSetAuthToken();
            }
            authToken = stringRedisTemplate.opsForValue().get(ClipWebConstants.AUTH_TOKEN);
            List<ClipWebContentInfo> contentInfoList = doGetUrlList(title, authToken);
            final CodeBuilder<String> codeBuilder = catCodeUtil.getStringCodeBuilder("at", false);
            GroupAccountInfo accountInfo = event.getAccountInfo();
            String atAccountInfo = codeBuilder.key("code").value(accountInfo.getAccountCode()).build();
            StringBuilder contentInfo = new StringBuilder();
            for (ClipWebContentInfo content : contentInfoList) {
                contentInfo.append(content.getTitle()).append("->").append(content.getUrlContent()).append("\n");
            }
            String template = """
                    = = = 亮哥小弟提示你 = = =
                            %s   
                            %s    
                    = = = = = = = = = = = =                
                            """;
            sender.SENDER.sendGroupMsgAsync(groupCode, String.format(template, contentInfo, atAccountInfo));
        }
    }

    private List<ClipWebContentInfo> doGetUrlList(String title, String authToken) {
        var contentListResponse = HttpClient
                .get(ClipWebConstants.BASIC_URI + "/contentList")
                .header("ApiToken", authToken)
                .queryString("title", title)
                .queryString("current", 1)
                .queryString("size", 100)
                .asBean(ClipWebResponse.class);
        Object data = contentListResponse.getData();
        JSONObject jsonObject = JSONArray.parseObject(JSON.toJSONString(data));
        JSONArray records = jsonObject.getJSONArray("records");
        List<ClipWebContentInfo> contentList = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            JSONObject record = records.getJSONObject(i);
            String t = String.valueOf(record.get("title"));
            String u = String.valueOf(record.get("urlContent"));
            contentList.add(new ClipWebContentInfo(t, u));
        }
        return contentList;
    }

}